"""
增强的视频流服务 - 支持真实流处理
集成WVP-Pro真实流URL获取和VideoFrameExtractor进行帧提取
实现流状态监控和管理功能
"""
from typing import Optional, List, Dict, Any, AsyncGenerator
from datetime import datetime, timedelta
import logging
import asyncio
from sqlalchemy.orm import Session

from schemas.video_stream import (
    VideoStreamRequest, VideoStreamResponse, VideoSnapshotRequest, 
    VideoSnapshotResponse, VideoRecordRequest, VideoRecordResponse,
    StreamProtocol, StreamQuality, VideoStreamStatus, StreamQualityInfo,
    MultiStreamRequest, MultiStreamResponse, StreamStatistics
)
from services.integration.wvp_integration_service import WVPIntegrationService
from services.video_processing.frame_extractor import VideoFrameExtractor, create_frame_extractor
from repositories.camera_repository import CameraRepository
from core.config import get_settings
import numpy as np

logger = logging.getLogger(__name__)
settings = get_settings()


class VideoStreamService:
    """增强的视频流服务类 - 支持真实流处理"""
    
    def __init__(self):
        self._stream_cache: Dict[str, Dict[str, Any]] = {}
        self._cache_ttl = settings.STREAM_CACHE_TTL
        self._statistics: Dict[str, StreamStatistics] = {}
        
        # 实时流处理相关
        self._active_streams: Dict[str, VideoFrameExtractor] = {}  # camera_id -> extractor
        self._stream_tasks: Dict[str, asyncio.Task] = {}  # camera_id -> processing task
        self._stream_status: Dict[str, Dict[str, Any]] = {}  # camera_id -> status info
    
    async def get_stream_url(
        self, 
        request: VideoStreamRequest,
        db: Session
    ) -> Optional[VideoStreamResponse]:
        """获取摄像头视频流地址 - 集成WVP-Pro真实流"""
        try:
            logger.info(f"处理摄像头流请求: {request.camera_id}")
            
            # 检查缓存
            cache_key = f"{request.camera_id}_{request.protocol}_{request.quality}"
            if cache_key in self._stream_cache:
                cached_data = self._stream_cache[cache_key]
                if datetime.now() < cached_data["expires_at"]:
                    logger.debug(f"返回缓存的流地址: {request.camera_id}")
                    return cached_data["response"]
            
            # 获取摄像头信息
            camera_repo = CameraRepository(db)
            camera = camera_repo.get_by_id(int(request.camera_id))
            
            if not camera:
                logger.error(f"摄像头不存在: {request.camera_id}")
                return None
            
            # 通过WVP集成服务获取真实流URL
            wvp_service = WVPIntegrationService(db)
            real_stream_url = await wvp_service.get_stream_url(camera.id)
            
            # 获取实际的流信息
            resolution = "1920x1080"
            bitrate = 2000
            fps = 25
            
            if not real_stream_url:
                logger.warning(f"无法获取摄像头 {request.camera_id} 的真实流URL，返回模拟地址")
                # 降级到模拟流
                real_stream_url = f"http://localhost:8000/stream/{request.camera_id}/index.m3u8"
            else:
                # 如果有真实流，尝试获取流的实际参数
                try:
                    # 创建临时帧提取器来获取流信息
                    temp_extractor = VideoFrameExtractor(real_stream_url, camera_id=request.camera_id)
                    if await temp_extractor.start():
                        stream_info = temp_extractor.get_stream_info()
                        if stream_info.get("status") == "connected":
                            width = stream_info.get("width", 1920)
                            height = stream_info.get("height", 1080)
                            resolution = f"{width}x{height}"
                            fps = int(stream_info.get("actual_fps", 25))
                        await temp_extractor.stop()
                except Exception as e:
                    logger.warning(f"获取摄像头 {request.camera_id} 流参数失败: {e}")
            
            # 构建响应
            response = VideoStreamResponse(
                camera_id=request.camera_id,
                stream_url=real_stream_url,
                protocol=request.protocol,
                quality=request.quality,
                resolution=resolution,
                bitrate=bitrate,
                fps=fps,
                expires_at=datetime.now() + timedelta(hours=1)
            )
            
            # 缓存结果
            self._stream_cache[cache_key] = {
                "response": response,
                "expires_at": datetime.now() + timedelta(seconds=self._cache_ttl)
            }
            
            logger.info(f"成功获取摄像头 {request.camera_id} 的流地址: {real_stream_url}")
            return response
            
        except Exception as e:
            logger.error(f"获取视频流失败: {e}")
            return None
    
    async def capture_snapshot(
        self, 
        request: VideoSnapshotRequest,
        db: Session
    ) -> Optional[VideoSnapshotResponse]:
        """捕获视频截图"""
        try:
            logger.info(f"处理摄像头截图请求: {request.camera_id}")
            
            # 返回模拟的截图响应
            return VideoSnapshotResponse(
                camera_id=request.camera_id,
                snapshot_url=f"http://localhost:8000/snapshots/{request.camera_id}_{int(datetime.now().timestamp())}.jpg",
                width=request.width or 1280,
                height=request.height or 720,
                file_size=245760,
                created_at=datetime.now(),
                expires_at=datetime.now() + timedelta(days=1)
            )
        except Exception as e:
            logger.error(f"截图失败: {e}")
            return None
    
    async def create_record(
        self, 
        request: VideoRecordRequest,
        db: Session
    ) -> Optional[VideoRecordResponse]:
        """创建视频录像"""
        try:
            logger.info(f"处理摄像头录像请求: {request.camera_id}")
            
            duration = int((request.end_time - request.start_time).total_seconds())
            
            # 返回模拟的录像响应
            return VideoRecordResponse(
                camera_id=request.camera_id,
                record_url=f"http://localhost:8000/records/{request.camera_id}_{int(request.start_time.timestamp())}.mp4",
                start_time=request.start_time,
                end_time=request.end_time,
                duration=duration,
                file_size=duration * 1024 * 1024,  # 假设每秒1MB
                quality=request.quality,
                created_at=datetime.now(),
                expires_at=datetime.now() + timedelta(days=7)
            )
        except Exception as e:
            logger.error(f"录像失败: {e}")
            return None
    
    async def get_stream_status(self, camera_id: str) -> Optional[VideoStreamStatus]:
        """获取视频流状态"""
        try:
            logger.info(f"获取摄像头状态: {camera_id}")
            
            # 返回模拟的状态
            return VideoStreamStatus(
                camera_id=camera_id,
                is_online=True,
                current_viewers=0,
                available_qualities=[
                    StreamQualityInfo(
                        quality=StreamQuality.HIGH,
                        resolution="1920x1080",
                        bitrate=2000,
                        fps=25
                    )
                ],
                last_frame_time=datetime.now(),
                error_message=None
            )
        except Exception as e:
            logger.error(f"获取流状态失败: {e}")
            return None
    
    async def get_multi_stream(
        self, 
        request: MultiStreamRequest,
        db: Session
    ) -> Optional[MultiStreamResponse]:
        """获取多路视频流"""
        try:
            logger.info(f"处理多路流请求: {len(request.camera_ids)} 个摄像头")
            
            streams = []
            for camera_id in request.camera_ids:
                stream_request = VideoStreamRequest(
                    camera_id=camera_id,
                    protocol=request.protocol,
                    quality=request.quality
                )
                stream = await self.get_stream_url(stream_request, db)
                if stream:
                    streams.append(stream)
            
            return MultiStreamResponse(
                streams=streams,
                layout=request.layout or "auto",
                total_count=len(streams)
            )
        except Exception as e:
            logger.error(f"获取多路流失败: {e}")
            return None
    
    def get_statistics(self, camera_id: str) -> Optional[StreamStatistics]:
        """获取流统计信息"""
        try:
            if camera_id in self._statistics:
                return self._statistics[camera_id]
            
            # 如果有活跃的流处理，返回实际统计信息
            if camera_id in self._active_streams:
                extractor = self._active_streams[camera_id]
                stream_info = extractor.get_stream_info()
                stats = stream_info.get("stats", {})
                
                return StreamStatistics(
                    camera_id=camera_id,
                    total_viewers=1,  # 实时处理算作1个观看者
                    peak_viewers=1,
                    total_duration=0,
                    bytes_sent=0,
                    frames_sent=stats.get("frames_extracted", 0),
                    error_count=stats.get("reconnections", 0),
                    last_error=None,
                    created_at=datetime.now(),
                    updated_at=datetime.now()
                )
            
            # 返回模拟的统计信息
            return StreamStatistics(
                camera_id=camera_id,
                total_viewers=0,
                peak_viewers=0,
                total_duration=0,
                bytes_sent=0,
                frames_sent=0,
                error_count=0,
                last_error=None,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
        except Exception as e:
            logger.error(f"获取统计信息失败: {e}")
            return None
    
    async def start_real_time_processing(self, camera_id: str, db: Session) -> bool:
        """启动实时流处理"""
        try:
            logger.info(f"启动摄像头 {camera_id} 的实时流处理")
            
            # 检查是否已经在处理
            if camera_id in self._active_streams:
                logger.warning(f"摄像头 {camera_id} 已在进行实时处理")
                return True
            
            # 获取摄像头信息
            camera_repo = CameraRepository(db)
            camera = camera_repo.get_by_id(int(camera_id))
            
            if not camera:
                logger.error(f"摄像头不存在: {camera_id}")
                return False
            
            # 获取流URL
            request = VideoStreamRequest(camera_id=camera_id)
            stream_response = await self.get_stream_url(request, db)
            
            if not stream_response:
                logger.error(f"无法获取摄像头 {camera_id} 的流URL")
                # 更新摄像头状态为错误
                camera_repo.update_status(camera.id, "error")
                return False
            
            # 创建帧提取器
            extractor = VideoFrameExtractor(
                stream_url=stream_response.stream_url,
                target_fps=settings.VIDEO_PROCESSING_FPS,
                camera_id=camera_id
            )
            
            # 启动帧提取器
            if not await extractor.start():
                logger.error(f"无法启动摄像头 {camera_id} 的帧提取器")
                # 更新摄像头状态为离线
                camera_repo.update_status(camera.id, "offline")
                return False
            
            # 保存到活跃流列表
            self._active_streams[camera_id] = extractor
            
            # 启动处理任务
            task = asyncio.create_task(self._process_stream_frames(camera_id, db))
            self._stream_tasks[camera_id] = task
            
            # 启动健康监控任务
            monitor_task = asyncio.create_task(self._monitor_stream_health(camera_id, db))
            self._stream_tasks[f"{camera_id}_monitor"] = monitor_task
            
            # 更新状态
            self._stream_status[camera_id] = {
                "status": "active",
                "started_at": datetime.now(),
                "stream_url": stream_response.stream_url,
                "target_fps": settings.VIDEO_PROCESSING_FPS,
                "last_health_check": datetime.now(),
                "health_status": "healthy",
                "error_count": 0,
                "last_error": None
            }
            
            # 更新摄像头状态为在线
            camera_repo.update_status(camera.id, "online")
            
            logger.info(f"摄像头 {camera_id} 实时流处理启动成功")
            return True
            
        except Exception as e:
            logger.error(f"启动摄像头 {camera_id} 实时流处理失败: {e}")
            # 更新摄像头状态为错误
            try:
                camera_repo = CameraRepository(db)
                camera = camera_repo.get_by_id(int(camera_id))
                if camera:
                    camera_repo.update_status(camera.id, "error")
            except:
                pass
            return False
    
    async def stop_real_time_processing(self, camera_id: str) -> bool:
        """停止实时流处理"""
        try:
            logger.info(f"停止摄像头 {camera_id} 的实时流处理")
            
            # 停止处理任务
            if camera_id in self._stream_tasks:
                task = self._stream_tasks[camera_id]
                task.cancel()
                try:
                    await task
                except asyncio.CancelledError:
                    pass
                del self._stream_tasks[camera_id]
            
            # 停止健康监控任务
            monitor_task_key = f"{camera_id}_monitor"
            if monitor_task_key in self._stream_tasks:
                monitor_task = self._stream_tasks[monitor_task_key]
                monitor_task.cancel()
                try:
                    await monitor_task
                except asyncio.CancelledError:
                    pass
                del self._stream_tasks[monitor_task_key]
            
            # 停止帧提取器
            if camera_id in self._active_streams:
                extractor = self._active_streams[camera_id]
                await extractor.stop()
                del self._active_streams[camera_id]
            
            # 更新状态
            if camera_id in self._stream_status:
                self._stream_status[camera_id]["status"] = "stopped"
                self._stream_status[camera_id]["stopped_at"] = datetime.now()
                self._stream_status[camera_id]["health_status"] = "stopped"
            
            logger.info(f"摄像头 {camera_id} 实时流处理已停止")
            return True
            
        except Exception as e:
            logger.error(f"停止摄像头 {camera_id} 实时流处理失败: {e}")
            return False
    
    async def _process_stream_frames(self, camera_id: str, db: Session):
        """处理视频流帧的内部方法"""
        try:
            extractor = self._active_streams.get(camera_id)
            if not extractor:
                return
            
            logger.info(f"开始处理摄像头 {camera_id} 的视频帧")
            frame_count = 0
            last_log_time = datetime.now()
            
            async for frame in extractor.extract_frames():
                if camera_id not in self._active_streams:
                    # 流已被停止
                    break
                
                frame_count += 1
                
                # 定期记录处理状态
                current_time = datetime.now()
                if (current_time - last_log_time).total_seconds() > 60:  # 每分钟记录一次
                    logger.info(f"摄像头 {camera_id} 已处理 {frame_count} 帧")
                    last_log_time = current_time
                
                # 更新流状态中的帧计数
                if camera_id in self._stream_status:
                    self._stream_status[camera_id]["frames_processed"] = frame_count
                    self._stream_status[camera_id]["last_frame_time"] = current_time
                
                # 这里可以集成AI处理逻辑
                # 目前只是记录帧处理
                logger.debug(f"处理摄像头 {camera_id} 的帧，尺寸: {frame.shape}")
                
                # 可以在这里调用AI批处理器
                # await self._process_frame_with_ai(camera_id, frame)
                
        except Exception as e:
            logger.error(f"处理摄像头 {camera_id} 视频帧时发生错误: {e}")
            # 更新错误状态
            if camera_id in self._stream_status:
                self._stream_status[camera_id]["error_count"] += 1
                self._stream_status[camera_id]["last_error"] = str(e)
                self._stream_status[camera_id]["health_status"] = "error"
        finally:
            logger.info(f"摄像头 {camera_id} 帧处理任务结束，共处理 {frame_count} 帧")
    
    async def _monitor_stream_health(self, camera_id: str, db: Session):
        """监控流健康状态"""
        try:
            logger.info(f"开始监控摄像头 {camera_id} 的流健康状态")
            camera_repo = CameraRepository(db)
            
            while camera_id in self._active_streams:
                try:
                    extractor = self._active_streams.get(camera_id)
                    if not extractor:
                        break
                    
                    # 检查流健康状态
                    is_healthy = extractor.is_healthy()
                    current_time = datetime.now()
                    
                    if camera_id in self._stream_status:
                        self._stream_status[camera_id]["last_health_check"] = current_time
                        
                        if is_healthy:
                            self._stream_status[camera_id]["health_status"] = "healthy"
                            # 更新摄像头状态为在线
                            camera = camera_repo.get_by_id(int(camera_id))
                            if camera and camera.status != "online":
                                camera_repo.update_status(camera.id, "online")
                        else:
                            self._stream_status[camera_id]["health_status"] = "unhealthy"
                            self._stream_status[camera_id]["error_count"] += 1
                            
                            # 尝试重启流
                            logger.warning(f"摄像头 {camera_id} 流不健康，尝试重启")
                            if await self._restart_unhealthy_stream(camera_id, db):
                                logger.info(f"摄像头 {camera_id} 流重启成功")
                            else:
                                logger.error(f"摄像头 {camera_id} 流重启失败")
                                # 更新摄像头状态为离线
                                camera = camera_repo.get_by_id(int(camera_id))
                                if camera:
                                    camera_repo.update_status(camera.id, "offline")
                    
                    # 等待下次检查
                    await asyncio.sleep(30)  # 每30秒检查一次
                    
                except Exception as e:
                    logger.error(f"监控摄像头 {camera_id} 健康状态时发生错误: {e}")
                    await asyncio.sleep(10)  # 出错时短暂等待
                    
        except Exception as e:
            logger.error(f"摄像头 {camera_id} 健康监控任务异常: {e}")
        finally:
            logger.info(f"摄像头 {camera_id} 健康监控任务结束")
    
    async def _restart_unhealthy_stream(self, camera_id: str, db: Session) -> bool:
        """重启不健康的流"""
        try:
            # 停止当前流
            if camera_id in self._active_streams:
                extractor = self._active_streams[camera_id]
                await extractor.stop()
                del self._active_streams[camera_id]
            
            # 等待一小段时间
            await asyncio.sleep(2)
            
            # 重新获取流URL并启动
            request = VideoStreamRequest(camera_id=camera_id)
            stream_response = await self.get_stream_url(request, db)
            
            if not stream_response:
                return False
            
            # 创建新的帧提取器
            extractor = VideoFrameExtractor(
                stream_url=stream_response.stream_url,
                target_fps=settings.VIDEO_PROCESSING_FPS,
                camera_id=camera_id
            )
            
            if await extractor.start():
                self._active_streams[camera_id] = extractor
                
                # 重启处理任务
                if camera_id in self._stream_tasks:
                    old_task = self._stream_tasks[camera_id]
                    if not old_task.done():
                        old_task.cancel()
                
                task = asyncio.create_task(self._process_stream_frames(camera_id, db))
                self._stream_tasks[camera_id] = task
                
                # 更新状态
                if camera_id in self._stream_status:
                    self._stream_status[camera_id]["status"] = "active"
                    self._stream_status[camera_id]["health_status"] = "healthy"
                    self._stream_status[camera_id]["restarted_at"] = datetime.now()
                
                return True
            
            return False
            
        except Exception as e:
            logger.error(f"重启摄像头 {camera_id} 流时发生错误: {e}")
            return False
    
    async def get_real_time_stream_status(self, camera_id: str) -> Dict[str, Any]:
        """获取实时流处理状态"""
        try:
            if camera_id not in self._stream_status:
                return {
                    "status": "inactive", 
                    "camera_id": camera_id,
                    "health_status": "unknown",
                    "stream_health": False
                }
            
            status_info = self._stream_status[camera_id].copy()
            
            # 添加实时信息
            if camera_id in self._active_streams:
                extractor = self._active_streams[camera_id]
                stream_info = extractor.get_stream_info()
                is_healthy = extractor.is_healthy()
                
                status_info.update({
                    "stream_health": is_healthy,
                    "stream_info": stream_info,
                    "extractor_stats": stream_info.get("stats", {}),
                    "connection_status": stream_info.get("status", "unknown")
                })
                
                # 计算运行时长
                if "started_at" in status_info:
                    uptime = (datetime.now() - status_info["started_at"]).total_seconds()
                    status_info["uptime_seconds"] = uptime
                    status_info["uptime_formatted"] = self._format_uptime(uptime)
            else:
                status_info.update({
                    "stream_health": False,
                    "connection_status": "disconnected"
                })
            
            # 添加任务状态
            task_status = {}
            if camera_id in self._stream_tasks:
                task = self._stream_tasks[camera_id]
                task_status["processing_task"] = {
                    "running": not task.done(),
                    "cancelled": task.cancelled(),
                    "exception": str(task.exception()) if task.done() and task.exception() else None
                }
            
            monitor_task_key = f"{camera_id}_monitor"
            if monitor_task_key in self._stream_tasks:
                monitor_task = self._stream_tasks[monitor_task_key]
                task_status["monitor_task"] = {
                    "running": not monitor_task.done(),
                    "cancelled": monitor_task.cancelled(),
                    "exception": str(monitor_task.exception()) if monitor_task.done() and monitor_task.exception() else None
                }
            
            status_info["task_status"] = task_status
            
            return status_info
            
        except Exception as e:
            logger.error(f"获取摄像头 {camera_id} 实时流状态失败: {e}")
            return {
                "status": "error", 
                "camera_id": camera_id, 
                "error": str(e),
                "health_status": "error",
                "stream_health": False
            }
    
    def _format_uptime(self, seconds: float) -> str:
        """格式化运行时长"""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}"
    
    async def get_active_streams(self) -> List[str]:
        """获取所有活跃的实时流"""
        return list(self._active_streams.keys())
    
    async def restart_stream(self, camera_id: str, db: Session) -> bool:
        """重启指定摄像头的流处理"""
        try:
            logger.info(f"重启摄像头 {camera_id} 的流处理")
            
            # 先停止
            await self.stop_real_time_processing(camera_id)
            
            # 等待一小段时间
            await asyncio.sleep(1)
            
            # 重新启动
            return await self.start_real_time_processing(camera_id, db)
            
        except Exception as e:
            logger.error(f"重启摄像头 {camera_id} 流处理失败: {e}")
            return False
    
    async def batch_start_streams(self, camera_ids: List[str], db: Session) -> Dict[str, bool]:
        """批量启动多个摄像头的实时流处理"""
        results = {}
        
        # 限制并发数量
        semaphore = asyncio.Semaphore(10)  # 最多同时启动10个流
        
        async def start_single_stream(camera_id: str):
            async with semaphore:
                results[camera_id] = await self.start_real_time_processing(camera_id, db)
        
        # 并发启动所有流
        tasks = [start_single_stream(camera_id) for camera_id in camera_ids]
        await asyncio.gather(*tasks, return_exceptions=True)
        
        logger.info(f"批量启动流处理完成，成功: {sum(results.values())}/{len(camera_ids)}")
        return results
    
    async def batch_stop_streams(self, camera_ids: List[str]) -> Dict[str, bool]:
        """批量停止多个摄像头的实时流处理"""
        results = {}
        
        # 并发停止所有流
        tasks = []
        for camera_id in camera_ids:
            if camera_id in self._active_streams:
                tasks.append(self.stop_real_time_processing(camera_id))
                results[camera_id] = True
            else:
                results[camera_id] = False
        
        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)
        
        logger.info(f"批量停止流处理完成，处理: {len(tasks)} 个流")
        return results
    
    async def cleanup_inactive_streams(self):
        """清理不活跃的流"""
        try:
            inactive_streams = []
            
            for camera_id, extractor in self._active_streams.items():
                if not extractor.is_healthy():
                    inactive_streams.append(camera_id)
            
            for camera_id in inactive_streams:
                logger.warning(f"清理不健康的流: {camera_id}")
                await self.stop_real_time_processing(camera_id)
            
            logger.info(f"清理了 {len(inactive_streams)} 个不活跃的流")
            
        except Exception as e:
            logger.error(f"清理不活跃流时发生错误: {e}")
    
    async def get_all_stream_status(self) -> Dict[str, Dict[str, Any]]:
        """获取所有流的状态信息"""
        try:
            all_status = {}
            
            # 获取所有活跃流的状态
            for camera_id in self._active_streams.keys():
                all_status[camera_id] = await self.get_real_time_stream_status(camera_id)
            
            # 添加已停止但有状态记录的流
            for camera_id in self._stream_status.keys():
                if camera_id not in all_status:
                    all_status[camera_id] = await self.get_real_time_stream_status(camera_id)
            
            return all_status
            
        except Exception as e:
            logger.error(f"获取所有流状态失败: {e}")
            return {}
    
    async def get_stream_performance_metrics(self) -> Dict[str, Any]:
        """获取流处理性能指标"""
        try:
            total_streams = len(self._active_streams)
            healthy_streams = 0
            total_frames = 0
            total_errors = 0
            
            for camera_id, extractor in self._active_streams.items():
                if extractor.is_healthy():
                    healthy_streams += 1
                
                stream_info = extractor.get_stream_info()
                stats = stream_info.get("stats", {})
                total_frames += stats.get("frames_extracted", 0)
                
                if camera_id in self._stream_status:
                    total_errors += self._stream_status[camera_id].get("error_count", 0)
            
            return {
                "total_active_streams": total_streams,
                "healthy_streams": healthy_streams,
                "unhealthy_streams": total_streams - healthy_streams,
                "health_rate": (healthy_streams / total_streams * 100) if total_streams > 0 else 0,
                "total_frames_processed": total_frames,
                "total_errors": total_errors,
                "average_fps": self._calculate_average_fps(),
                "system_load": {
                    "active_tasks": len(self._stream_tasks),
                    "cached_streams": len(self._stream_cache)
                }
            }
            
        except Exception as e:
            logger.error(f"获取性能指标失败: {e}")
            return {}
    
    def _calculate_average_fps(self) -> float:
        """计算平均帧率"""
        try:
            if not self._active_streams:
                return 0.0
            
            total_fps = 0
            count = 0
            
            for extractor in self._active_streams.values():
                stream_info = extractor.get_stream_info()
                actual_fps = stream_info.get("actual_fps", 0)
                if actual_fps > 0:
                    total_fps += actual_fps
                    count += 1
            
            return total_fps / count if count > 0 else 0.0
            
        except Exception as e:
            logger.error(f"计算平均帧率失败: {e}")
            return 0.0
    
    async def force_restart_all_streams(self, db: Session) -> Dict[str, bool]:
        """强制重启所有活跃流"""
        try:
            logger.info("开始强制重启所有活跃流")
            camera_ids = list(self._active_streams.keys())
            
            # 先停止所有流
            stop_results = await self.batch_stop_streams(camera_ids)
            
            # 等待一段时间
            await asyncio.sleep(3)
            
            # 重新启动所有流
            start_results = await self.batch_start_streams(camera_ids, db)
            
            logger.info(f"强制重启完成，成功重启: {sum(start_results.values())}/{len(camera_ids)}")
            return start_results
            
        except Exception as e:
            logger.error(f"强制重启所有流失败: {e}")
            return {}


# 创建全局实例
video_stream_service = VideoStreamService()